package com.shopping_back.serviceImpl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shopping_back.pojo.dto.EvaluationDTO;
import com.shopping_back.pojo.dto.EvaluationSubmitDTO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shopping_back.pojo.entity.Evaluation;
import com.shopping_back.mapper.EvaluationMapper;
import com.shopping_back.pojo.vo.EvaluationVO;
import com.shopping_back.service.IEvaluationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shopping_back.util.SensitiveWordFilter;
import org.springframework.stereotype.Service;
import com.shopping_back.exception.BizException;
import com.shopping_back.mapper.OrderItemMapper;
import com.shopping_back.mapper.OrderMainMapper;
import com.shopping_back.pojo.entity.OrderItem;
import com.shopping_back.pojo.entity.OrderMain;
import lombok.RequiredArgsConstructor;

import java.util.List;

/**
 * <p>
 * 商品评价表 服务实现类
 * </p>
 *
 * @author Jack
 * @since 2025-07-12
 */
@Service
@RequiredArgsConstructor
public class EvaluationServiceImpl extends ServiceImpl<EvaluationMapper, Evaluation> implements IEvaluationService {
    private final EvaluationMapper evaluationMapper;

    @Override
    public Page<Evaluation> listAll(Integer pageNum, Integer pageSize, Integer auditStatus) {
        Page<Evaluation> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Evaluation> qw = new LambdaQueryWrapper<>();
        if (auditStatus != null) {
            qw.eq(Evaluation::getAuditStatus, auditStatus);
        }
        qw.orderByDesc(Evaluation::getCreateTime);
        return this.page(page, qw);
    }

    private final OrderItemMapper orderItemMapper;
    private final OrderMainMapper orderMainMapper;
    private final SensitiveWordFilter sensitiveWordFilter;

    @Override
    public Page<EvaluationVO> getProductEvaluations(Long spuId, int page, int size) {
        Page<com.shopping_back.pojo.vo.EvaluationVO> mpPage = new Page<>(page, size);
        baseMapper.selectProductEvaluations(mpPage, spuId);
        return mpPage;
    }

    @Override
    public void submitEvaluation(EvaluationSubmitDTO dto, Long userId) {
        // 参数合法性校验
        if (dto.getOrderItemId() == null) {
            throw new BizException("缺少订单项ID");
        }

        // 判断是否已评价
        boolean exists = lambdaQuery()
                .eq(Evaluation::getOrderItemId, dto.getOrderItemId())
                .exists();
        if (exists) {
            throw new BizException("该商品已评价");
        }

        Long uid = userId;
        if (uid == null) {
            OrderItem oi = orderItemMapper.selectById(dto.getOrderItemId());
            if (oi == null) {
                throw new BizException("订单项不存在");
            }
            OrderMain om = orderMainMapper.selectById(oi.getOrderId());
            if (om == null) {
                throw new BizException("订单不存在");
            }
            uid = om.getUserId();
        }

        if (uid == null) {
            throw new BizException("无法确定用户ID");
        }

        // 内容违禁词校验（加强版）
        if (dto.getContent() != null) {
            if (sensitiveWordFilter.hasBadWord(dto.getContent())) {
                throw new BizException("评价内容包含违规词汇");
            }
        }

        Evaluation eval = new Evaluation();
        eval.setOrderItemId(dto.getOrderItemId());
        eval.setUserId(uid);
        eval.setContent(dto.getContent());
        eval.setScore(dto.getScore());
        // 将逗号分隔的图片地址转换为 JSON 数组字符串，兼容 MySQL JSON 类型
        if (dto.getImages() != null && !dto.getImages().isBlank()) {
            String jsonArr = cn.hutool.json.JSONUtil.toJsonStr(java.util.Arrays.asList(dto.getImages().split(",")));
            eval.setImages(jsonArr);
        }
        eval.setAuditStatus(1); // 默认审核通过
        eval.setCreateTime(java.time.LocalDateTime.now());
        eval.setUpdateTime(java.time.LocalDateTime.now());

        save(eval);
    }
    @Override
    public void deleteByAdmin(Long id) {
        Evaluation eval = this.getById(id);
        if (eval == null) throw new RuntimeException("评论不存在");
        if (eval.getAuditStatus() == 1) {
            eval.setAuditStatus(0);
            this.updateById(eval);
        }
    }

    @Override
    public void approve(Long id) {
        Evaluation eval = this.getById(id);
        if (eval == null) throw new RuntimeException("评论不存在");
        if (eval.getAuditStatus() == 0) {
            eval.setAuditStatus(1);
            this.updateById(eval);
        }
    }

    @Override
    public Page<EvaluationDTO> getEvaluations(Long merchantId, int page, int size) {
        Page<EvaluationDTO> pageInfo = new Page<>(page, size);
        List<EvaluationDTO> evaluations = evaluationMapper.selectEvaluationsByMerchantId(merchantId, size, (page - 1) * size);
        pageInfo.setRecords(evaluations);
        pageInfo.setTotal(evaluationMapper.countEvaluationsByMerchantId(merchantId));
        return pageInfo;
    }
}
